package com.haidong.web;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/req3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //因为post请求才会有文本流,所以设置流编码只对post请求有效
        //要想解决get请求的中文乱码问题,要把获取的到文本反编码然后重解码
        //tomcat8以后的版本中get的编码默认为utf-8,不会乱码
        String method = req.getMethod();

        if("GET".equals(method)){
            String name = req.getParameter("username");
            System.out.println("只修改了流编码格式,post请求中文参数正常");
            System.out.println("只修改了" + name);
            name = new String(name.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
        }else if("POST".equals(method)){
            req.setCharacterEncoding("utf-8");
            System.out.println(req.getParameter("username"));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
